package com.mytest.retrofit;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.mytest.R;
import com.mytest.bean.BaseEntity;
import com.mytest.bean.LoginBean;
import com.mytest.bean.PostBean;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Locale;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author jzs created 2017/5/17
 *         Retrofit 测试
 */
public class RetrofitActivity extends Activity {

    @BindView(R.id.tv_login)
    TextView tv;

    @BindView(R.id.et_account)
    EditText et_account;

    @BindView(R.id.et_pwd)
    EditText et_pwd;

    @OnClick(R.id.btn)
    void login() {
        creatRE();
    }

    @OnClick(R.id.btn_post)
    void test_post() {
        testPost();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrofit);
        ButterKnife.bind(this);
    }

    /**
     * @author jzs created 2017/5/17
     * 构造 Retrofit
     */
    private void creatRE() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(final String message) {
                //打印retrofit日志

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText(tv.getText() + message);
                    }
                });
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .connectTimeout(5000, TimeUnit.SECONDS)
                .readTimeout(5000, TimeUnit.SECONDS)
                .writeTimeout(5000, TimeUnit.SECONDS)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://www.yigongkeji.cc:8010/")
//                .baseUrl("http://wx.weixinxjj.com/xjjapi5/api.php?f=xjj_person_share_red")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        String account = et_account.getText().toString().trim();
        String pwd = et_pwd.getText().toString().trim();

        LoginService loginService = retrofit.create(LoginService.class);
        Call<LoginBean> bean = loginService.login(account, MD5.getMD5ofStr(pwd).toLowerCase(Locale.getDefault()));
        bean.enqueue(new Callback<LoginBean>() {
            @Override
            public void onResponse(Call<LoginBean> call, Response<LoginBean> response) {
                try {
                    Log.e("sk", "getCode: " + response.body().getCode());
                    Log.e("sk", "getMsg: " + response.body().getMsg());
                    Log.e("sk", "onResponse: " + response.body().toString());

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<LoginBean> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    /**
     * @author Jzs created 2017/6/27
     * post json数据
     */
    private void testPost() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(final String message) {
                //打印retrofit日志

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText(tv.getText() + message);
                    }
                });
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .connectTimeout(5000, TimeUnit.SECONDS)
                .readTimeout(5000, TimeUnit.SECONDS)
                .writeTimeout(5000, TimeUnit.SECONDS)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
//                .baseUrl("http://www.yigongkeji.cc:8010/")
                .baseUrl("http://wx.weixinxjj.com/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        PostService postService = retrofit.create(PostService.class);


        JSONObject params = new JSONObject();
        try {
            params.put("userId", "18205930592");
            params.put("token", "d8e16380103a48309745a89604d3b23a");
            params.put("status", "0");
            params.put("page", "1");
            params.put("pageNum", "10");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"),
                params.toString());

        Call<ResponseBody> bean = postService.share(requestBody);
        bean.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String string = response.body().string().trim();

                    Log.e("sk", "onResponse: " + string);
                    Gson gson = new Gson();
                    PostBean bean = gson.fromJson(string, PostBean.class);
                    Log.e("sk", "bean: " + bean.toString());

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }
}
